#include <hwProtection.h>
#include <appConfig.h>

hwProtIsrCallback_t ovVoltageCallback = NULL;
hwProtIsrCallback_t uvVoltageCallback = NULL;

void VBAT_Handler(void)
{
    if (PMUA_SFRS->VBATCTRL.UV == 1 && uvVoltageCallback){
        PMUA_SFRS->VBATIRQ.CLEAR.UV  = 1;
        uvVoltageCallback();
    }
    if (PMUA_SFRS->VBATCTRL.OV == 1 && ovVoltageCallback){
        PMUA_SFRS->VBATIRQ.CLEAR.OV   = 1;
        ovVoltageCallback();
    }
}


void HW_PROT_SetOverTmperature(OverTempThres_t threshold, OverTempAction_t action)
{
//    CRGA_SFRS->OVTEMPCONFIG.OVTEMPLEVEL = threshold;
//    CRGA_SFRS->OVTEMPACTION.OVTEMP      = action;
//    CRGA_SFRS->OVTEMPCONFIG.OVTEMPENA   = 1; // enable ov temperature action
}

void HW_PROT_RegisterOVTemperatureIRQ(hwProtIsrCallback_t callback)
{
//    ovTemperatureCallback = callback;
//    CRGA_SFRS->RESETCTRL.OVTEMPFLAGCLR = 1;
//    NVIC_EnableIRQ(OVTEMP_IRQn);
}

void HW_PROT_UnRegisterOVTemperatureIRQ(void)
{
//    ovTemperatureCallback = NULL;
//    CRGA_SFRS->RESETCTRL.OVTEMPFLAGCLR = 1;
//    NVIC_DisableIRQ(OVTEMP_IRQn);
}


void HW_PROT_SetOverVoltage(OverVoltThres_t threshold)
{
    PMUA_SFRS->VBATCTRL.OVLEVEL = threshold;
    PMUA_SFRS->VBATCTRL.OVMENA  = 1;
}

void HW_PROT_RegisterOverVoltageIRQ(hwProtIsrCallback_t callback)
{
    ovVoltageCallback             = callback;
    PMUA_SFRS->VBATIRQ.CLEAR.OV   = 1;
    PMUA_SFRS->VBATIRQ.ENABLE.OV  = 1;
    NVIC_DisableIRQ(VBAT_IRQn);
}

void HW_PROT_UnRegisterOverVoltageIRQ(void)
{
    ovVoltageCallback = NULL;
    PMUA_SFRS->VBATIRQ.CLEAR.OV   = 1;
    PMUA_SFRS->VBATIRQ.ENABLE.OV  = 0;
    NVIC_DisableIRQ(VBAT_IRQn);
}

void HW_PROT_SetUnderVoltage(UnderVoltThres_t threshold)
{
    PMUA_SFRS->VBATCTRL.UVLEVEL = threshold;
    PMUA_SFRS->VBATCTRL.UVMENA  = 1;
}

void HW_PROT_RegisterUnderVoltageIRQ(hwProtIsrCallback_t callback)
{
    uvVoltageCallback           = callback;
    PMUA_SFRS->VBATIRQ.CLEAR.UV  = 1;
    PMUA_SFRS->VBATIRQ.ENABLE.UV  = 1;
    NVIC_EnableIRQ(VBAT_IRQn);
}

void HW_PROT_UnRegisterUnderVoltageIRQ(void)
{
    ovVoltageCallback = NULL;
    PMUA_SFRS->VBATIRQ.CLEAR.UV  = 1;
    PMUA_SFRS->VBATIRQ.ENABLE.UV  = 0;
    NVIC_DisableIRQ(VBAT_IRQn);
}


bool HW_PROT_BattVoltIsTooLow(void)
{
    return (PMUA_SFRS->VBATCTRL.UV == 1);
}

bool HW_PROT_BattVoltIsTooHigh(void)
{
    return (PMUA_SFRS->VBATCTRL.OV == 1);
}

bool HW_PROT_ChipIsOverHeat(void)
{
//    return (CRGA_SFRS->RESETCTRL.OVTEMPFLAG == 1);
    return false;
}

